#include "date.h"
#include "rtc.h"
#include "system.h"

#define LOG_TAG "date"

static RTC_DateTypeDef hdate = {0};
static RTC_TimeTypeDef htime = {0};

void date_get_reboot_flag(void)
{
    if (__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST) != RESET)
    {
        log_e("发生电源复位 ");
    }
    else if (__HAL_RCC_GET_FLAG(RCC_FLAG_SFTRST) != RESET)
    {
        log_e("发生软件复位 ");
    }
    else if (__HAL_RCC_GET_FLAG(RCC_FLAG_IWDGRST) != RESET)
    {
        log_e("发生IWDG看门狗复位 ");
    }
    else if (__HAL_RCC_GET_FLAG(RCC_FLAG_WWDGRST) != RESET)
    {
        log_e("发生WWDG看门狗复位 ");
    }
    else if (__HAL_RCC_GET_FLAG(RCC_FLAG_LPWRRST) != RESET)
    {
        log_e("发生低功耗复位 ");
    }
    else if (__HAL_RCC_GET_FLAG(RCC_FLAG_PINRST) != RESET)
    {
        log_e("发生引脚复位 ");
    }
}

void date_init(void)
{
    __HAL_RCC_PWR_CLK_ENABLE();
    HAL_PWR_EnableBkUpAccess();
    if (HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_REG) != RTC_BKP_DATA)//检测是否存在备份
    {
        HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_REG, RTC_BKP_DATA);
        hdate.Year = 0x20;
        hdate.Month = 0x01;
        hdate.Date = 0x01;
        htime.Hours = 0x12;
        htime.Minutes = 0x00;
        htime.Seconds = 0x00;
        HAL_RTC_SetDate(&hrtc, &hdate, RTC_FORMAT_BCD);
        HAL_RTC_SetTime(&hrtc, &htime, RTC_FORMAT_BCD);
        log_a("RTC 时间初始化 ");
    }
    HAL_RTC_WaitForSynchro(&hrtc);
}

void date_get(Date_t *date)
{
    if (HAL_RTC_WaitForSynchro(&hrtc) != HAL_OK)
    {
        date->hour = 18;
        return;
    }
    HAL_RTC_GetDate(&hrtc, &hdate, RTC_FORMAT_BIN);
    HAL_RTC_GetTime(&hrtc, &htime, RTC_FORMAT_BIN);
    date->year = hdate.Year + 2000;
    date->month = hdate.Month;
    date->day = hdate.Date;
    date->hour = htime.Hours;
    date->minute = htime.Minutes;
    date->second = htime.Seconds;
}

void date_print(void)
{
    Date_t date;
    date_get(&date);
    log_d("%04d-%02d-%02d %02d:%02d:%02d", date.year, date.month, date.day, date.hour, date.minute, date.second);
}